package com.mikey.io;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.locks.*;
import java.util.stream.IntStream;

/**
 * @author :Mikey
 * @description : 带缓冲区的生产者消费者模式
 * @create :2022-10-31 10:45:00
 */
public class Demo {
    public static void main(String[] args) {
        FileDoing fileDoing = new FileDoing();
        for (int i = 0; i <10; i++) {
            new Thread(()->{
                fileDoing.read();
            },String.valueOf(i)).start();
        }
        for (int i = 0; i <10; i++) {
            new Thread(()->{
                fileDoing.write();
            },String.valueOf(i)).start();
        }
    }
}
class FileDoing{
    ReadWriteLock lock=new ReentrantReadWriteLock();
    boolean flag=false;
    public void read(){
        lock.readLock().lock();
        try {
            FileReader fileReader = new FileReader("D:\\demo\\a.txt");
            BufferedReader bufferedReader = new BufferedReader(fileReader);
            char[] s = new char[100];
            bufferedReader.read(s);
            bufferedReader.close();
            System.out.println(Thread.currentThread().getName()+"我在读");
            System.out.println(Thread.currentThread().getName()+"这是我读的内容"+s);
        } catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            lock.readLock().unlock();
        }
    }
    public void write(){
        lock.writeLock().lock();
        try {
            FileWriter fileWriter = new FileWriter("D:\\demo\\b.txt");
            BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
            String str=UUID.randomUUID().toString();
            bufferedWriter.write(str);
            bufferedWriter.close();
            System.out.println(Thread.currentThread().getName()+"我在写");
            System.out.println(Thread.currentThread().getName()+"这是我写入的内容"+str);
        } catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            lock.writeLock().unlock();
        }
    }
}